package biz.almas.uycnr.crawler.crawler.handler;

import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;

import biz.almas.uycnr.crawler.entity.Channel;
import biz.almas.uycnr.crawler.utils.CnrValidator;

/**
 * @Description:
 * @Copyright: Copyright (c) 2015 XinJiang Almas Software All Rights Reserved
 * @Company: XinJiang Almas Software
 * @author Ansar786 Nov 19, 2015
 * @version V1.0
 * @history:
 * 
 */
public class ChannelXmlHandler extends DefaultHandler {

	// 存储正在解析的元素的数据
	private Map<String, String> map = new HashMap<String, String>();
	// 栏目集合
	private List<Channel> channels = new ArrayList<Channel>();

	public int langId;
	// 开始解析的元素
	private final String NODE_NAME = "Channel";
	// 正在解析的元素的名字
	private String currentTag = null;
	// 正在解析的元素的元素值
	private String currentValue = null;

	private long beginTime;
	private long endTime;

	// 定义日志输出对象
	private static Logger logger = Logger.getLogger(ChannelXmlHandler.class);

	/**
	 * 构造方法
	 */
	public ChannelXmlHandler() {
		super();
	}

	/**
	 * 解析文档开始
	 */
	public void startDocument() throws SAXException {
		logger.info("开始解析XML数据");
		beginTime = System.currentTimeMillis();
	}

	/**
	 * 解析文档结束
	 */
	public void endDocument() throws SAXException {
		endTime = System.currentTimeMillis();
		logger.info("结束解析XML数据结束，共耗时" + (endTime - beginTime) / 1000 + "秒");
	}

	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		currentTag = qName;
		if (NODE_NAME.equals(currentTag)) {
			map.clear();
		}
	}

	public void characters(char[] ch, int start, int length)
			throws SAXException {
		if (currentTag != null) {
			currentValue = new String(ch, start, length);
			// 如果内容不为空和空格，也不是换行符则将该元素名和值和存入map中
			if (currentValue != null && !currentValue.trim().equals("")
					&& !currentValue.trim().equals("\n")) {
				map.put(currentTag.trim(), currentValue.trim());
			}
			// 当前的元素已解析过，将其置空用于下一个元素的解析
			currentTag = null;
			currentValue = null;
		}
	}

	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		if (NODE_NAME.equals(qName)) {
			addList();
		}
	}

	private void addList() {
		try {
			Channel channel = new Channel();
			channel.setIsContainsChildren(CnrValidator.parseInt(map
					.get("ISCONTAINSCHILDREN")));
			channel.setChnlId(CnrValidator.parseInt(map.get("chnlid"),
					"栏目编号有误！"));
			channel.setChnlName(map.get("chnlname"));
			channel.setChnlDesc(CnrValidator.parseString(map.get("chnldesc"),
					"栏目维文名称不能为空"));
			channel.setChnlType(CnrValidator.parseInt(map.get("CHNLTYPE")));
			channel.setChnlOrder(CnrValidator.parseInt(map.get("CHNLORDER")));
			channel.setStatus(CnrValidator.parseInt(map.get("status")));
			channel.setParentId(CnrValidator.parseInt(map.get("Parentid")));
			channel.setOperTime(CnrValidator.string2DateTime(map
					.get("OPERTIME")));
			channel.setCrtime(CnrValidator.string2DateTime(map.get("CRTIME")));
			channel.setDocumentsUrl(map.get("documents-url"));
			channel.setLangId(langId);
			channel.setShowPic(0);

			channels.add(channel);

		} catch (ParseException e) {
			logger.error(e.toString() + "\t" + map.get("chnlname"));
		}
	}

	public List<Channel> getChannels() {
		return channels;
	}

	public InputSource resolveEntity(String publicId, String systemId)
			throws IOException, SAXException {
		return super.resolveEntity(publicId, systemId);
	}

	public void notationDecl(String name, String publicId, String systemId)
			throws SAXException {
		super.notationDecl(name, publicId, systemId);
	}

	public void unparsedEntityDecl(String name, String publicId,
			String systemId, String notationName) throws SAXException {
		super.unparsedEntityDecl(name, publicId, systemId, notationName);
	}

	public void setDocumentLocator(Locator locator) {
		super.setDocumentLocator(locator);
	}

	public void startPrefixMapping(String prefix, String uri)
			throws SAXException {
		super.startPrefixMapping(prefix, uri);
	}

	public void endPrefixMapping(String prefix) throws SAXException {
		super.endPrefixMapping(prefix);
	}

	public void ignorableWhitespace(char[] ch, int start, int length)
			throws SAXException {
		super.ignorableWhitespace(ch, start, length);
	}

	public void processingInstruction(String target, String data)
			throws SAXException {
		super.processingInstruction(target, data);
	}

	public void skippedEntity(String name) throws SAXException {
		super.skippedEntity(name);
	}

	public void warning(SAXParseException e) throws SAXException {
		super.warning(e);
	}

	public void error(SAXParseException e) throws SAXException {
		super.error(e);
	}

	public void fatalError(SAXParseException e) throws SAXException {
		super.fatalError(e);
	}
}
